import React, { useState } from "react"
import { Card, Form, Input, Button, Checkbox, message } from "antd"
import Logo from "@/assets/logo.png"
import { useDispatch } from "react-redux"
import { login } from "@/store/action/login"
import { useHistory, useLocation } from "react-router-dom"
import styles from "./index.module.scss"

export default function Login() {
  const location = useLocation()
  const dispatch = useDispatch()
  // 登录按钮状态
  const [loading, setLoading] = useState(false)
  // 路由跳转
  const history = useHistory()
  // 当表单校验通过 就会执行 携带数据
  const onFinish = async (values) => {
    setLoading(true)
    // 发送请求进行登录
    try {
      await dispatch(login(values))
      message.success("登陆成功", 1, () => {
        const from = location.state ? location.state.from : "/home"
        history.replace(from)
      })
    } catch (error) {
      message.error(error.response.data.message, 1, () => {
        setLoading(false)
      })
    }
  }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={Logo} alt="" />
        {/* 表单 */}
        <Form
          autoComplete="off"
          size="large"
          validateTrigger={["onChange", "onBlur"]}
          onFinish={onFinish}
          initialValues={{ mobile: "13911111111", code: "246810", agree: true }}>
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: "手机号不能为空" },
              { pattern: /^1[3-9]\d{9}$/, message: "手机号格式错误" },
            ]}>
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: "验证码不能为空" },
              { pattern: /^\d{6}$/, message: "验证码格式错误" },
            ]}>
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) => {
                  if (value) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error("请同意"))
                  }
                },
              },
            ]}>
            <Checkbox>我已阅读并同意</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
